package com.hsmpay.mobile.action.terminal;

import com.hsmpay.common.util.NumberUtil;
import com.hsmpay.mobile.action.base.MobileBaseAction;
import com.hsmpay.mobile.pojo.terminal.TerminalVersion;
import com.hsmpay.mobile.service.terminal.TerminalVersionService;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 错误日志 action
 *
 * @author 颜铃璋
 * @date 2013-1-18
 */
@Controller("terminalVersionAction")
@Scope("prototype")
public class TerminalVersionAction extends MobileBaseAction {
    private static final long serialVersionUID = 4685508381751184994L;
    private static Logger log = Logger.getLogger(TerminalVersionAction.class);

    @Resource(name = "terminalVersionService")
    private TerminalVersionService<TerminalVersion, Long> terminalVersionService;

    private Long vId;//终端类型ID
    private String version;//版本号 v1.0.0.1
    private String machineType;//机器类型

    /**
     * 检测版本
     *
     * @return
     * @throws Exception
     */
    public String checkVersion() throws Exception {
        log.debug("--- checkVersion() start ---");
        JSONObject js = JSONObject.fromObject(getRequest().getAttribute(FC_DATA));
        terminalTypeId = Long.parseLong(js.getString("terminalTypeId"));
        clientType = Integer.parseInt(js.getString("clientType"));
        roleId = Long.parseLong(js.getString("roleId"));
        if (js.containsKey("version"))
            version = js.getString("version");
        if (js.containsKey("machineType"))
            machineType = js.getString("machineType");

        log.debug("terminalTypeId = " + terminalTypeId);
        log.debug("clientType = " + clientType);
        log.debug("version = " + version);
        log.debug("roleId = " + roleId);
        log.debug("machineType = " + machineType);
        //version = "1.0.0.0.3";
        if (null == terminalTypeId) {
            log.warn("检测版本时, 传入参数terminalTypeId为空");
            sendAppErrorMsg("6001", "terminalTypeId");
            return null;
        }
        if (null == clientType) {
            log.warn("检测版本时, 传入参数clientType为空");
            sendAppErrorMsg("6001", "clientType");
            return null;
        }
        if (StringUtils.isBlank(version)) {
            log.warn("检测版本时, 传入参数version为空");
            sendAppErrorMsg("6001", "version");
            return null;
        }
        try {
            Map<String, Object> resultMap = new LinkedHashMap<String, Object>();
            resultMap.put("version", version);
            resultMap.put("reqCode", "0000");
            resultMap.put("reqMsg", "检测版本时,没有检查到版本！");

            //蓝牙版
            if (null != machineType && "3".equals(machineType)) {
                log.info("检测版本时,遇到蓝牙pos 版本");
//				resultMap = getLanYaVersion(resultMap);//
//				sendAppMsg(resultMap);
//				return null;
                if (terminalTypeId.intValue() == 1) terminalTypeId = 3001L;
                if (terminalTypeId.intValue() == 9) terminalTypeId = 3002L;
                if (terminalTypeId.intValue() == 21) terminalTypeId = 3003L;
                if (terminalTypeId.intValue() == 34) terminalTypeId = 3004L;
            }

            //查询当前版本
            TerminalVersion nowVersion = terminalVersionService.searchNowVersion(version, terminalTypeId, clientType, roleId);
            if (null == nowVersion) {
                sendAppMsg(resultMap);
                log.info("检测版本时,当前版本不存在！");
                return null;
            }
            //查询最新版本信息
            TerminalVersion latestVersion = terminalVersionService.searchLatestVersion(terminalTypeId, clientType, roleId, nowVersion.getVersionType());

            if (null != latestVersion) {
                if (version.equals(latestVersion.getVersion())) {//|| clientType.intValue() == 3 如果 版本相同  直接返回版本号
                    sendAppMsg(resultMap);
                    log.info("检测版本时,没有需要更新版本");
                } else {//有新版本
                    resultMap.put("version", latestVersion.getVersion());
                    //String SYSTEM_BACK_BASE_URL = "http://10.0.0.66:8080/proOneMobile/";//Constant.getAttribute("SYSTEM_BACK_BASE_URL");
                    Integer downloadSrc = latestVersion.getDownloadSrc();
                    String filePath = null;
                    if (downloadSrc != null && downloadSrc == 2){
                        if (StringUtils.isNotBlank(latestVersion.getThirdURL())){
                            filePath = latestVersion.getThirdURL();
                        }
                    }else{
                        if (StringUtils.isNotBlank(latestVersion.getFilePath())){
                            filePath = latestVersion.getFilePath();
                        }else if (StringUtils.isNotBlank(latestVersion.getPlistUrl())){
                            filePath = latestVersion.getPlistUrl();
                        }
                    }
//                    if (StringUtils.isNotBlank(filePath) && (3 == latestVersion.getClientType().intValue() || 4 == latestVersion.getClientType().intValue())) {//如果是 iphone 暂时就给 plis文件
//                        if (StringUtils.isNotEmpty(latestVersion.getPlistUrl())) {
//                            if (terminalTypeId == 70){
//                                filePath = "https://marhui001.b0.upaiyun.com/appdownload/" + terminalTypeId + "_" + roleId + "/v" + latestVersion.getVersion() + "/v2015_9_28/app.plist&random=" + NumberUtil.generateRandomString(10);
//                            }else{
//                                filePath = "https://marhui001.b0.upaiyun.com/appdownload/" + terminalTypeId + "_" + roleId + "/v" + latestVersion.getVersion() + "/v2015_9_24/app.plist&random=" + NumberUtil.generateRandomString(10);
//                            }
//                        } else {
//                            if (terminalTypeId == 70){
//                                filePath = "https://marhui001.b0.upaiyun.com/appdownload/" + terminalTypeId + "_" + roleId + "/v" + latestVersion.getVersion() + "/v2015_9_28/app.plist&random=" + NumberUtil.generateRandomString(10);
//                            }else{
//                                filePath = "https://marhui001.b0.upaiyun.com/appdownload/" + terminalTypeId + "_" + roleId + "/v" + latestVersion.getVersion() + "/v2015_9_24/app.plist&random=" + NumberUtil.generateRandomString(10);
//                            }
//                        }
//                    }
//                    if (StringUtils.isBlank(filePath) && (3 == latestVersion.getClientType().intValue() || 4 == latestVersion.getClientType().intValue())) {
//                        filePath = latestVersion.getThirdURL();
//                    }

                    resultMap.put("filePath", filePath);
                    //resultMap.put("filePath", "terminalVersion/terminalVersionAction_downloadVersion.action?vId="+latestVersion.getId());
                    resultMap.put("isForce", latestVersion.getIsForce());
                    resultMap.put("description", StringUtils.isBlank(latestVersion.getDescription()) ? "" : latestVersion.getDescription());

                    resultMap.put("reqCode", "0000");
                    resultMap.put("reqMsg", "检测版本时,检查到需要更新版本！");
                    sendAppMsg(resultMap);
                    log.info("检测版本时,检查到需要更新版本");
                }
            } else {//如果没有查询到版本
                sendAppMsg(resultMap);
                log.info("检测版本时,没有检查到版本");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            log.debug("--- checkVersion() end ---");
        }
        return null;
    }

//	public static Map<String,String> versionMap = new HashMap<String, String>();//终端类型_终端角色_客户端  版本号
//	public static Map<String,String> durlMap = new HashMap<String, String>();//终端类型_终端角色_客户端  版本号
//	static{
//		versionMap.put("1_2_2", "1.0.0.3.7");//花生米费率版  安卓
//		versionMap.put("1_3_2", "1.0.0.3.7");//花生米封顶版  安卓
//		versionMap.put("1_2_3", "1.0.0.3.7");//花生米费率版  ios
//		versionMap.put("1_3_3", "1.0.0.3.7");//花生米封顶版  ios
//		
//		versionMap.put("9_2_2", "1.0.0.0.8");//方孔联费率版 安卓
//		versionMap.put("9_3_2", "1.0.0.0.8");//方孔联封顶版 安卓
//		versionMap.put("9_2_3", "1.0.0.0.8");//方孔联费率版 ios
//		versionMap.put("9_3_3", "1.0.0.0.8");//方孔联封顶版 ios
//		
//		versionMap.put("21_2_2", "1.0.0.0.4");//光宇星费率版 安卓
//		versionMap.put("21_3_2", "1.0.0.0.4");//光宇星封顶版 安卓
//		versionMap.put("21_2_3", "1.0.0.0.4");//光宇星费率版 ios
//		versionMap.put("21_3_3", "1.0.0.0.4");//光宇星封顶版 ios
//		
//		
//		durlMap.put("1_2_2", "https://plistfiles.b0.upaiyun.com/lanya/1/android/2.apk");//花生米费率版  安卓
//		durlMap.put("1_3_2", "https://plistfiles.b0.upaiyun.com/lanya/1/android/3.apk");//花生米封顶版  安卓
//		durlMap.put("1_2_3", "https://plistfiles.b0.upaiyun.com/lanya/1/iphone/2.plist");//花生米费率版  ios
//		durlMap.put("1_3_3", "https://plistfiles.b0.upaiyun.com/lanya/1/iphone/3.plist");//花生米封顶版  ios
//		
//		durlMap.put("9_2_2", "https://plistfiles.b0.upaiyun.com/lanya/9/android/2.apk");//方孔联费率版 安卓  
//		durlMap.put("9_3_2", "https://plistfiles.b0.upaiyun.com/lanya/9/android/3.apk");//方孔联封顶版 安卓
//		durlMap.put("9_2_3", "https://plistfiles.b0.upaiyun.com/lanya/9/iphone/2.plist");//方孔联费率版 ios
//		durlMap.put("9_3_3", "https://plistfiles.b0.upaiyun.com/lanya/9/iphone/3.plist");//方孔联封顶版 ios
//		
//		durlMap.put("21_2_2", "https://plistfiles.b0.upaiyun.com/lanya/21/android/2.apk");//光宇星费率版 安卓
//		durlMap.put("21_3_2", "https://plistfiles.b0.upaiyun.com/lanya/21/android/3.apk");//光宇星封顶版 安卓
//		durlMap.put("21_2_3", "https://plistfiles.b0.upaiyun.com/lanya/21/iphone/2.plist");//光宇星费率版 ios
//		durlMap.put("21_3_3", "https://plistfiles.b0.upaiyun.com/lanya/21/iphone/3.plist");//光宇星封顶版 ios
//	}
//	
//	private Map<String, Object> getLanYaVersion(Map<String, Object> resultMap){
//		String key = terminalTypeId+"_"+roleId+"_"+clientType;
//		if(versionMap.containsKey(key) && versionMap.get(key).equals(version)){
//			resultMap.put("reqCode", "0000");
//			resultMap.put("reqMsg", "检测版本时,没有检查到需要更新版本！");
//		}else{
//			resultMap.put("version", versionMap.get(key));
//			if(durlMap.containsKey(key)){
//				resultMap.put("filePath", durlMap.get(key));
//				resultMap.put("isForce", 1);
//				resultMap.put("description", "v"+versionMap.get(key)+"版本更新了以下功能:\n1、美化了部分页面；2、修改了部分bug；");
//				resultMap.put("reqCode", "0000");
//				resultMap.put("reqMsg", "检测版本时,检查到需要更新版本！");
//			}else{
//				resultMap.put("reqCode", "0000");
//				resultMap.put("reqMsg", "检测版本时,没有检查到需要更新版本！");
//			}
//		}
//		return resultMap;
//	}


    /**
     * http://10.0.0.66:8080/proOneMobile/terminalVersion/terminalVersionAction_downloadVersion.action?vId=181
     * http://10.0.0.66:8080/proOneMobile/terminalVersion/terminalVersionAction_downloadVersion.action?vId=181
     * 下载版本
     *
     * @return
     * @throws Exception
     */
    public String downloadVersion() throws Exception {
        log.debug("--- downloadVersion() start ---");
        log.debug("vId = " + vId);
        if (null == vId) {
            log.warn("检测版本时, 传入参数vId为空");
            sendAppErrorMsg("6001", "vId");
            return null;
        }

        try {
            TerminalVersion latestVersion = new TerminalVersion();
            latestVersion.setId(vId);
            latestVersion = terminalVersionService.searchEntity(latestVersion);

            if (null != latestVersion) {
                //HttpServletRequest request = getRequest();
                HttpServletResponse response = getResponse();
                String filePath = latestVersion.getFilePath();
                String relPath = getRealPath(filePath);
                String fileName = filePath.substring(filePath.lastIndexOf('/') + 1);

                String contentType = "application/vnd.iphone";//ios
                if (latestVersion.getClientType().equals(2)) {
                    contentType = "application/vnd.android.package-archive";//android
                    log.debug("contentType = " + contentType);

                    BufferedReader brIn = new BufferedReader(new InputStreamReader(new FileInputStream(relPath), "UTF-8"));
                    //清空输出流
                    response.reset();
                    //设置响应头和下载保存的文件名
                    response.setHeader("content-disposition", "attachment;filename=" + fileName);
                    //定义输出类型
                    response.setHeader("Content-Type", contentType + "; charset=UTF-8");
                    response.setContentType(contentType);

                    PrintWriter pw = response.getWriter();
                    String nexts = null;
                    String s = brIn.readLine();
                    while (s != null) {
                        nexts = brIn.readLine();
                        if (nexts != null) {
                            pw.println(s);
                        } else {
                            pw.print(s);
                        }
                        s = nexts;
                    }
                    pw.flush();
                    pw.close();
                    //response.flushBuffer();//强行将响应缓存中的内容发送到目的地
                } else {
                    filePath = "itms-services://?action=download-manifest&url=" + "http://10.0.0.66:8080/proOneMobile/" + filePath.substring(0, filePath.lastIndexOf(".")) + ".plist";//"itms-services://?action=download-manifest&url="+SYSTEM_BACK_BASE_URL+filePath.substring(0, filePath.lastIndexOf("."))+".plist";
                    getRequest().setAttribute("downloadVersionIos", filePath);
                    return "downloadVersionIos";
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            log.debug("--- downloadVersion() end ---");
        }
        return null;
    }

    //---------------------set get start--------------------
    public void setVId(Long id) {
        vId = id;
    }
    //---------------------set get end----------------------
}
